package com.zqh.forum.controller;

import com.zqh.forum.common.AppResult;
import com.zqh.forum.common.ResultCode;
import com.zqh.forum.exception.ApplicationException;
import com.zqh.forum.model.Board;
import com.zqh.forum.services.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/board")
@Tag(name = "板块的详情页")
public class BoardController {

    //从配置文件中读取数值，如果在配置文件中找不到该配置文件的话，默认值是9
    @Value("${zqh-forum.index.board-num:9}")
    private Integer indexBoardByNum;

    @Autowired
    private IBoardService boardService;

    /**
     * 查询首页板块列表
     * @return
     */
    @Operation(summary = "获取首页板块列表")
    @GetMapping("/toList")
    public AppResult<List<Board>> toList (){
        //首先打印存在的数据条数
        log.info("首页板块的个数为：" + indexBoardByNum);
        //调用service
        List<Board> boards = boardService.selectByNum(indexBoardByNum);
        //判断查询的数据是否为空
        if(boards == null){
            boards = new ArrayList<>();
        }
        //返回结果
        return AppResult.success(boards);
    }

    @GetMapping("/getById")
    @Operation(summary = "获取板块的信息")
    @Parameter(name = "id",description = "板块id")
    public AppResult<Board> getById(@RequestParam("id") @NonNull Long id){
        //调用session
        Board board = boardService.selectById(id);
        //判断板块是否已经删除或者不存在
        if(board == null || board.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        return AppResult.success(board);
    }
}
